package cc.magicjson.mall.order.application.service;

import cc.magicjson.mall.order.application.command.CreateOrderCommand;
import cc.magicjson.mall.order.application.command.OrderQuery;
import cc.magicjson.mall.order.application.command.PlaceOrderCommand;
import cc.magicjson.mall.order.domain.model.Order;
import cc.magicjson.mall.order.infrastructure.anticorruption.ProductPriceTranslator;
import cc.magicjson.mall.order.infrastructure.persistence.JpaOrderRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * OrderApplicationService 应用服务
 * 协调领域对象和基础设施服务
 */
@Service
public class OrderApplicationService {
	private final JpaOrderRepository jpaOrderRepository;
	private final ProductPriceTranslator productPriceTranslator;

	public OrderApplicationService(JpaOrderRepository jpaOrderRepository, ProductPriceTranslator productPriceTranslator) {
		this.jpaOrderRepository = jpaOrderRepository;
		this.productPriceTranslator = productPriceTranslator;
	}

	@Transactional
	public String createOrder(CreateOrderCommand command) {
		Order order = new Order(command.getCustomerId().id());
		for (CreateOrderCommand.OrderItem item : command.getItems()) {
			order.addProduct(
					item.getProductId(),
					item.getQuantity(),
					productPriceTranslator.translatePrice(item.getProductId())
			);
		}
		jpaOrderRepository.save(order);
		return order.getId().toString();
	}

	@Transactional
	public void placeOrder(PlaceOrderCommand command) {
		Order order = jpaOrderRepository.getReferenceById(command.orderId());
		order.place();
		jpaOrderRepository.save(order);
	}

	public OrderQuery getOrder(String orderId) {
		Order order = jpaOrderRepository.findById(orderId).get();
		return new OrderQuery(orderId, order.getStatus());
	}
}